<template>
    <div class="content">
        <div class="operation">
            办理人
            <el-select v-model="operator" size="mini" clearable filterable placeholder="请输入办理人信息" class="input-st">
                <el-option v-for="item in userOptions" :key="item.userCode" :value="item.userCode" :label="item.userName"></el-option>
            </el-select>
            <el-button size="mini" type="primary" @click="handleSearch('process')">查询</el-button>
            <el-button size="mini" type="primary" @click="handleSearch('exchange')">切换查询</el-button>
        </div>
        <div class="charts">
            <div class="charts-part1">
                <el-card v-for="item in cards" :key="item.title">
                    <TaskBarChart
                        :data="{
                            ...item,
                            type: currentType,
                            xData: taskXData[currentType],
                        }"
                        :ref="item.name"
                        @click-bar="barClick(item.name, $event)"
                    ></TaskBarChart>
                </el-card>
            </div>
            <div class="charts-part2">
                <el-card class="contract-protocol">
                    <ContractBarChart
                        ref="contract-protocol"
                        :data="contractData"
                        @time-change="handleSearch('contract', $event)"
                        @click-bar="barClick('contract-protocol', $event)"
                    ></ContractBarChart>
                </el-card>
                <div class="already-statistics">
                    <div class="operate">
                        <el-button :type="bgcColor.week ? 'primary' : 'text'" size="mini" @click="handleAlready('week')">本周</el-button>
                        <el-button :type="bgcColor.year ? 'primary' : 'text'" size="mini">年度</el-button>
                        <el-date-picker
                            v-model="alrParams.year"
                            @change="handleAlready('year')"
                            type="year"
                            size="mini"
                            placeholder="选择年"
                            style="width:75px"
                            value-format="yyyy"
                            format="yyyy"
                        >
                        </el-date-picker>
                        <el-button :type="bgcColor.month ? 'primary' : 'text'" size="mini">月度</el-button>
                        <el-date-picker
                            v-model="alrParams.month"
                            @change="handleAlready('month')"
                            type="month"
                            size="mini"
                            placeholder="选择月"
                            style="width:75px"
                            value-format="MM"
                            format="MM月"
                        ></el-date-picker>
                        <span>办理人</span>
                        <el-select v-model="alrParams.operator" size="mini" clearable filterable placeholder="办理人" style="width:95px">
                            <el-option v-for="item in userOptions" :key="item.userCode" :value="item.userCode" :label="item.userName"></el-option>
                        </el-select>
                        <!-- <el-input v-model="alrParams.operator" size="mini" placeholder="办理人"></el-input> -->
                        <el-button type="primary" size="mini" @click="handleSearch('alr')">查询</el-button>
                    </div>
                    <el-card class="alr-chart">
                        <TaskBarChart
                            :data="{ ...alrData, type: 'already-statistics' }"
                            ref="already-statistics"
                            @click-bar="barClick('already-statistics', $event)"
                        ></TaskBarChart>
                    </el-card>
                </div>
            </div>
        </div>
    </div>
</template>
<script lang="ts">
import { Vue, Component, Watch, Prop } from 'vue-property-decorator';
import ContractBarChart from './contract-bar-chart.vue';
import TaskBarChart from './task-bar-chart.vue';
import * as api from '../api/fund-pending-manage';
import { getUser } from '@/utils/user-util';
import DictionConstUtil from '../dict';
@Component({
    name: 'TaskStatistics',
    components: {
        TaskBarChart,
        ContractBarChart,
    },
})
// 视图
export default class TaskStatistics extends Vue {
    @Prop() activeValue: string;
    userOptions: any = [{ userCode: '', userName: '' }];
    // 已办任务参数
    alrParams = {
        weekFlag: true,
        year: '',
        month: '',
        operator: getUser().userCode,
    };

    // 已办任务查询参数背景色
    bgcColor = {
        week: true,
        year: false,
        month: false,
    };
    // 切换查询
    currentType: string = '1';
    taskXData = DictionConstUtil.contractDateType;
    // 办理人
    operator: string = getUser().userCode;
    contractHalfYearTime: string = '6'; // 6 近6月
    cards = [
        {
            title: '产品台账维护',
            name: 'funds',
            key: '1',
            data: [],
        },
        {
            title: '指标底稿维护',
            name: 'indicators',
            key: '2',
            data: [],
        },
        {
            title: '交易系统维护',
            name: 'trades',
            key: '3',
            data: [],
        },
        {
            title: '事后系统维护',
            name: 'afterwards',
            key: '4',
            data: [],
        },
    ];

    contractData: any = {
        title: '合同/协议统计',
        xData: [],
        data: { products: [], protocols: [], totals: [] },
    };
    alrData: any = {
        xData: ['产品台账', '指标底稿', '交易系统', '事后系统'],
        data: [],
        title: '已办任务统计',
    };
    chartInstanceArr: any = [];
    chartComponent: any[] = ['funds', 'indicators', 'trades', 'afterwards'];
    isFirst: boolean = true;
    @Watch('activeValue', { immediate: true })
    handleActiveValue() {
        if (this.activeValue === 'task-statistics') {
            if (this.isFirst) {
                this.getUser();
                this.getProcessData();
                this.getContractHalfYear();
                this.getAlrData();
                this.isFirst = false;
                this.$nextTick(() => {
                    this.chartComponent.forEach(ele => {
                        console.log(this.$refs[ele] as any, '(this.$refs[ele] as any)');
                        this.chartInstanceArr.push((this.$refs[ele][0] as any).chartInstance);
                    });

                    this.chartInstanceArr.push((this.$refs['contract-protocol'] as any).chartInstance);
                    this.chartInstanceArr.push((this.$refs['already-statistics'] as any).chartInstance);

                    window.addEventListener('resize', this.screenAdapter);
                    this.screenAdapter();
                });
            } else {
                this.screenAdapter();
            }
        }
    }

    // @Watch('contractHalfYearTime', { immediate: true })
    // handleContractHalfYearTime() {
    //     console.log('aaaaaaaaaaaa');
    //     this.getContractHalfYear();
    // }

    screenAdapter() {
        console.log('123456789');

        const titleFontSize = ((this.$refs['already-statistics'] as any).offsetWidth / 100) * 5.6;
        // 分辨率变化图表配置
        const adapterOption = {
            axisLabel: {
                textStyle: {
                    fontSize: titleFontSize,
                },
            },
            // 柱状条目
            series: [
                {
                    // barWidth: titleFontSize,
                    // 条目文字配置
                    // itemStyle: {
                    //   barBorderRadius: [titleFontSize / 2, titleFontSize / 2, 0, 0],
                    // }
                },
            ],
        };
        console.log(this.chartInstanceArr);
        this.chartInstanceArr.forEach(ele => {
            console.log(ele, 'ele');

            ele.setOption(adapterOption);
            // (this.$refs as any)['already-statistics'].extension(ele);
            ele.resize();
        });
    }

    destroyed() {
        window.removeEventListener('resize', this.screenAdapter);
    }

    // 查询
    handleSearch(type: string, time?: string) {
        if (type == 'process') {
            this.getProcessData();
        } else if (type == 'exchange') {
            this.currentType = this.currentType == '1' ? '2' : '1';
            this.getProcessData();
        } else if (type == 'contract') {
            if (time !== this.contractHalfYearTime) {
                // 近6月、近12月
                this.contractHalfYearTime = time;
                this.getContractHalfYear();
            }
        } else if (type == 'alr') {
            this.getAlrData();
        }
    }

    // 选择年度、月度
    handleAlready(type: string) {
        this.bgcColor[type] = true;
        if (type == 'week') {
            this.alrParams.weekFlag = true;
            // TODO  是否需要清除年月数据
            this.bgcColor.year = false;
            this.bgcColor.month = false;
            this.getAlrData();
        } else if (type == 'year' || type == 'month') {
            this.alrParams.weekFlag = false;
            this.bgcColor.week = false;
            console.log(this.alrParams[type], 'this.alrParams[type]');
            !this.alrParams[type] && (this.bgcColor[type] = false);
        }
    }

    // 产品待办进程
    getProcessData() {
        if (this.currentType == '1') {
            api.listByUploadDate({ sponsor: this.operator })
                .then((res: any) => {
                    if (res) {
                        for (let key in res) {
                            let obj = this.cards.find(item => item.name == key);
                            obj.data = res[key];
                        }
                    }
                })
                .catch(err => {
                    console.log(err, 'listByUploadDate');
                });
        } else {
            api.listByeffectDate({ sponsor: this.operator })
                .then((res: any) => {
                    if (res) {
                        for (let key in res) {
                            let obj = this.cards.find(item => item.name == key);
                            obj.data = res[key];
                        }
                    }
                    console.log(this.cards);
                })
                .catch(err => {
                    console.log(err, 'listByeffectDate');
                });
        }
    }
    // 已办任务统计
    getAlrData() {
        api.dealedList({
            ...this.alrParams,
            weekFlag: this.alrParams.weekFlag ? '1' : '0',
        })
            .then((res: any) => {
                this.alrData.data = res;
                console.log(res, 'res');
            })
            .catch(err => {
                console.log(err, 'dealedList');
            });
    }

    // 合同/协议统计
    getContractHalfYear() {
        api.contractHalfYear({ monthOrYear: '-' + this.contractHalfYearTime })
            .then((res: any) => {
                // res = {
                //     legCount: 0,
                //     monthBefore: [
                //         '202206',
                //         '202207',
                //         '202208',
                //         '202209',
                //         '202210',
                //         '202211',
                //         '202212',
                //         '202301',
                //         '202302',
                //         '202303',
                //         '202304',
                //         '202305',
                //     ],
                //     products: ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '3', '0'],
                //     protocols: ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '2', '1'],
                //     totals: ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1'],
                // };
                this.contractData.data = {
                    products: res.products,
                    protocols: res.protocols,
                    totals: res.totals,
                };
                this.contractData.xData = res.monthBefore;
                console.log(this.contractData, 'contractData');
            })
            .catch(err => {
                console.log(err, 'contractHalfYear');
            });
    }

    // 柱状图点击
    barClick(type: string, $event) {
        console.log(type, $event.params, '----------------------');
        const params = $event.params;
        if (type == 'contract-protocol') {
            // 跳转到合同明细tab
            this.$emit('tab-change', { name: 'contract-detail', params: $event.params });
        } else {
            // 跳转到任务明细tab
            this.$emit('tab-change', {
                name: 'task-detail',
                params: { ...$event.params, sponsor: params.status == '1' ? this.operator : this.alrParams.operator },
            });
        }
        // else if (type == 'already-statistics') {
        //     // 跳转到任务明细tab
        // }
    }

    // 主办人下拉数据
    getUser() {
        api.settingUser()
            .then((res: any) => {
                this.userOptions = res || [];
            })
            .catch(err => {
                console.log(err, 'settingUser');
            });
    }
}
</script>
<style lang="scss">
.content {
    min-height: 610px;
    height: 100%;
    .operation {
        .input-st {
            width: 220px;
            margin-right: 20px;
        }
    }
    .charts {
        margin-top: 20px;
        height: calc(100% - 50px);
        .charts-part1,
        .charts-part2 {
            background-color: #f2f2f2;
            height: 50%;
            padding: 10px;
        }
        .charts-part1 {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 5px;
        }
        .charts-part2 {
            margin-top: 10px;
            display: grid;
            grid-template-columns: 56fr 44fr;
            gap: 5px;
            .contract-protocol {
            }

            .already-statistics {
                height: 100%;
                .operate {
                    height: 30px;
                    line-height: 30px;
                    .el-icon-date {
                        display: none;
                    }

                    .el-button {
                        padding: 6px 2px;
                        &:last-child {
                            margin-left: 4px;
                        }
                    }
                    .el-input--prefix .el-input__inner {
                        padding-left: 10px;
                    }
                    .el-input--suffix .el-input__inner {
                        padding-right: 10px;
                    }
                    & > span {
                        margin: 0 8px;
                    }
                    & > button {
                        margin: 0 2px;

                        & > span {
                            color: #333;
                        }
                    }
                    & > .el-button--primary > span {
                        color: #fff;
                    }
                }
                .alr-chart {
                    height: calc(100% - 41px);
                    margin-top: 10px;
                }
            }
        }
    }
}

.title {
    height: 25px;
    line-height: 25px;
    overflow: hidden;

    > span {
        padding-left: 25px;
        font-size: 16px;
        font-weight: bold;
    }
}
.el-card .el-card__body {
    height: 100%;
    padding: 10px !important;
}
</style>
